package com.hooda.session;

import com.hooda.config.BoundSql;
import com.hooda.pojo.Configuration;
import com.hooda.pojo.MappedStatement;
import com.hooda.utils.GenericTokenParser;
import com.hooda.utils.ParameterMapping;
import com.hooda.utils.ParameterMappingTokenHandler;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangzp
 * @version 1.0, 2021/7/29
 */
public class SimpleExecutor implements Executor {

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... parameters) throws Exception {

        BoundSql boundSql = getBoundSql(mappedStatement.getSql());

        DataSource dataSource = configuration.getDataSource();
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        Class<?> parameterClass = getClassType(mappedStatement.getParameterType());
        for (int i = 0; i < boundSql.getParameterMappingList().size(); i++) {
            ParameterMapping parameterMapping = boundSql.getParameterMappingList().get(i);
            Field declaredField = parameterClass.getDeclaredField(parameterMapping.getContent());
            declaredField.setAccessible(true);
            Object value = declaredField.get(parameters[0]);
            preparedStatement.setObject(i+1, value);
        }

        ResultSet resultSet = preparedStatement.executeQuery();

        List<Object> result = new ArrayList<Object>();
        Class<?> resultClass = getClassType(mappedStatement.getResultType());
        while (resultSet.next()) {
            Object entity = resultClass.newInstance();

            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);

                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                propertyDescriptor.getWriteMethod().invoke(entity, resultSet.getObject(i));
            }
            result.add(entity);
        }
        return (List<E>) result;
    }

    @Override
    public int insert(Configuration configuration, MappedStatement mappedStatement, Object... parameters) throws Exception {
        return update(configuration, mappedStatement, parameters);
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... parameters) throws Exception {
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());

        DataSource dataSource = configuration.getDataSource();
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        Class<?> parameterClass = getClassType(mappedStatement.getParameterType());
        for (int i = 0; i < boundSql.getParameterMappingList().size(); i++) {
            ParameterMapping parameterMapping = boundSql.getParameterMappingList().get(i);
            Field declaredField = parameterClass.getDeclaredField(parameterMapping.getContent());
            declaredField.setAccessible(true);
            Object value = declaredField.get(parameters[0]);
            preparedStatement.setObject(i+1, value);
        }

        return preparedStatement.executeUpdate();
    }

    @Override
    public int delete(Configuration configuration, MappedStatement mappedStatement, Object... parameters) throws Exception {
        return update(configuration, mappedStatement, parameters);
    }

    private Class<?> getClassType(String name) throws ClassNotFoundException {
        if (name != null) {
            return Class.forName(name);
        }
        return null;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        return new BoundSql(parse, parameterMappingTokenHandler.getParameterMappings());
    }

}
